package blackpai.backend.aspects;

import blackpai.backend.dao.ManagerMapper;
import blackpai.backend.entity.Manager;
import blackpai.backend.entity.ManagerExample;
import blackpai.backend.util.MD5Util;
import blackpai.backend.vo.Result;
import blackpai.backend.vo.Token;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Aspect
@Configuration
public class LoginAspect {

    @Resource
    private ManagerMapper managerMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RestTemplate restTemplate;
    @Before("execution(* blackpai.backend.service.ManagerServiceImpl.managerLogin(..))")
    public Object around(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        ManagerExample managerExample = new ManagerExample();
        managerExample.createCriteria().andUsernameEqualTo(args[0].toString());
        List<Manager> managers = managerMapper.selectByExample(managerExample);
        if(args.length<2){
            throw new RuntimeException("用户名或密码不能为空");
        }
        if(managers.size()==0){
            throw new RuntimeException("账号不存在");
        }
        for (Manager manager : managers) {
            if(manager.getStatus()==0){
                if(manager.getPassword().equals(MD5Util.getMD5((manager.getSalt()+args[1])))){
                    return manager;
                }
                throw new RuntimeException("密码错误");
            }
            throw new RuntimeException("你的账号被封了");
        }
        return null;
    }

   /* @Around("execution(* blackpai.backend.service.ManagerServiceImpl.managerLogin(..))")
    public Object after(ProceedingJoinPoint joinPoint){
        Object result = null;
        try {
            result = joinPoint.proceed();
            String token = (String) request.getAttribute("token");
            System.out.println(token+"!!!!!!!");
            String forObject = restTemplate.getForObject("http://redis-server/redis/getToken?token="+token, String.class);
            if (forObject==null){
                throw new RuntimeException("请重新登陆");
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }*/

}
